package cn.izeno.wx.core

import java.util.*
import java.util.logging.Logger

/**
 * 自动刷新 component token
 */
class RefreshMiniProgramTokenTask private constructor() : TimerTask() {

  override fun run() {
    tokenManager.refresh().subscribe({
      logger.warning("刷新小程序 token 成功")
      tokenManager.save(it)
      timer?.schedule(RefreshMiniProgramTokenTask(), period)
    }, {
      logger.warning("刷新小程序 token 失败，将在1分钟后尝试。${it.message}")
      timer?.schedule(RefreshMiniProgramTokenTask(), 60 * 1000)
    })
  }

  companion object {
    private val logger = Logger.getGlobal()

    private var timer: Timer? = null
    private val period = 6600 * 1000L
    //    private var period = 120 * 1000L
    private lateinit var tokenManager: MiniProgramTokenManager

    @Synchronized
    fun start(refresher: MiniProgramTokenManager) {
      timer?.cancel()
      timer = Timer()

      tokenManager = refresher

      //  在 token 失效前十分钟执行刷新, 如果以失效, 1ms 后刷新
      tokenManager.current().subscribe {
        var delay: Long = it.expiredAt - System.currentTimeMillis() - 600 * 1000
        if (delay < 0) delay = 1
        timer?.schedule(RefreshMiniProgramTokenTask(), delay)
      }
    }

    @Synchronized
    fun stop() {
      timer?.cancel()
      timer = null
    }

    fun run() {
      RefreshMiniProgramTokenTask().run()
    }
  }
}